﻿using OA.IBLL;
using OA.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Security;

namespace OA.Mvc.Filters
{
	public class OAAuthFilterAttribute:AuthorizeAttribute
	{
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }
    }

    public class OAAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public ISysRoleService RoleService { get; set; }
        public ISysActionService ActionService { get; set; }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            // 如果方法被标注为 AllowAnonymous ，则放行
            if ( filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any())
            {
                return;
            }

            if (filterContext.HttpContext.User.Identity.IsAuthenticated) // 如果用户已登录
            {
                //当前访问的是那个控制器的方法
                var controller = filterContext.RouteData.Values["Controller"].ToString();

                controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                var action = filterContext.ActionDescriptor.ActionName;
                var method = filterContext.HttpContext.Request.HttpMethod;// 请求方式

                //用户是什么角色，有那些权限
                var user = filterContext.HttpContext.User.Identity as FormsIdentity;
                var userRoles= user.Ticket.UserData.Split(','); // 格式：“1，2，4”
                var allActions = new List<SysAction>();

                foreach(var rid in userRoles)
                {
                    var acs = filterContext.HttpContext.Cache[rid] as List<SysAction>;  // 根据角色id获取缓存中的权限
                    if(acs==null)
                    {
                        acs = (RoleService.GetEntityAsync(x => x.Id == int.Parse(rid))
                            .Result).SysActions.ToList();
                        // 缓存中保存一份
                        filterContext.HttpContext.Cache.Insert(rid, acs, null,DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration);
                    }
                    allActions = allActions.Union(acs).ToList(); // 并集
                }

                //var Actions=RoleService.GetList(x => userRoles.Contains(x.Id.ToString()))
                //    .Select(x => x.SysActions).ToList();
                //foreach (var acs in Actions)
                //{

                //    allActions = allActions.Union(acs).ToList(); // 并集
                //}
                // 如果拥有权限
                if ( allActions.Any(a => a.ActionName.ToUpper() == action.ToUpper() && a.ControllerName.ToUpper() == controller.ToUpper() && a.Method.ToUpper() == method.ToUpper()))
                {
                    return;  // 放行
                }
               else
                {
                    filterContext.Result = new RedirectResult("/noAction.html"); // 截断
                }


            }
            else // 用户没有登录
            {
                filterContext.Result = new RedirectResult("/account/login");
            }
            

            



            //用户权限是否包含当前方法
        }
    }
}